package com.testmanager.testmananger.practiseDemo;


import net.lingala.zip4j.core.ZipFile;

import net.lingala.zip4j.io.ZipInputStream;
import net.lingala.zip4j.model.FileHeader;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/practise")
//@CrossOrigin   //解决跨域问题
public class Upload {
    private final String basePath = "/opt/uploadfile/";

    @PostMapping("/upload")
    public List upload(HttpServletRequest request ,@RequestParam("user") String user,
                         @RequestParam(value = "file",required = false)MultipartFile file) throws Exception {

        //request.setCharacterEncoding("UTF-8");
            //String basePath = "/opt/uploadfile/";

       //java.util.zip.ZipFile files = new java.util.zip.ZipFile(file.getInputStream());




        if(!file.isEmpty() && file.getOriginalFilename().toUpperCase().contains(".ZIP")){

            String fileName = file.getOriginalFilename();
            String path = "";
            String realPath = request.getSession().getServletContext().getRealPath("/");
            List<String> fileNames = new ArrayList<>();
            String truefileNmae = user + "_" + fileName;
            path = "/opt/uploadfile/" + truefileNmae;





            File dest = new File(path);

          //  ZipInputStream zipInputStream = new ZipInputStream(file.getInputStream());

            ZipFile zipFile = new ZipFile(dest);
            zipFile.setFileNameCharset("GBK");
            try {
                file.transferTo(dest);
            } catch (IOException e) {

                e.printStackTrace();
                return null;
            }
            List<FileHeader> fileHeaders = zipFile.getFileHeaders();


            for(FileHeader fileHeader : fileHeaders){
              //  fileName.endsWith("/") || fileName.endsWith("\\\\") || fileName.endsWith("\\")
               if (!fileHeader.getFileName().endsWith(File.pathSeparator)){
                   fileNames.add(fileHeader.getFileName());
               }
           }




            return  fileNames;
        }
        return null;

    }



    @GetMapping("/getxml/{fileName}")
    public String getxml(@PathVariable("fileName")String xmlname) throws Exception {
        String encoding = "UTF-8";
        String realFileName = basePath + xmlname;
        File xmlFile = new File(realFileName);

        InputStreamReader reader = null;
        StringWriter writer = new StringWriter();

        try {
            if (encoding == null || "".equals(encoding.trim())) {
                reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
            } else {
                reader = new InputStreamReader(new FileInputStream(xmlFile));
            }
            //将输入流写入输出流
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = reader.read(buffer))) {
                writer.write(buffer, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null)
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        System.out.println(writer.toString());
        String temp =writer.toString();
        return temp;
    }




    @GetMapping("/download")
    public void download(HttpServletRequest req, HttpServletResponse rep) throws  Exception{
        String fileName = req.getParameter("fileName");// 设置文件名，根据业务需要替换成要下载的文件名
      //  String basePath = "/opt/uploadfile/";
//        String layerId = req.getParameter("layerId");
//        String downloadDir = req.getSession().getServletContext().getRealPath("/") +"upload/";
//        String savePath = req.getSession().getServletContext().getRealPath("/") +"download/";
//        downloadDir=downloadDir.substring(0,downloadDir.length()-1);
//        downloadDir=downloadDir+"\\";//下载目录


        String realPath=fileName;//
        System.out.println(realPath);
        File file = new File(realPath);//下载目录加文件名拼接成realpath
        if(file.exists()){ //判断文件父目录是否存在
//            response.setContentType("application/force-download");
            rep.setHeader("Content-Disposition",  String.format("attachment; fileName=\"%s\"", URLEncoder.encode(fileName, "UTF-8")));

            rep.setHeader("fileName",file.getName())   ;
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = rep.getOutputStream();
                fis = new FileInputStream(file);

                bis = new BufferedInputStream(fis);
              //  bis = new BufferedInputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }




    }





}
